﻿using Core.Base;
using lingopen.Foxconn.RFID.Sdk;
using Core.Com;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using Reader.SFC.Models;
using Core.Enums;
using Core.Interfaces;
using System.IO.Ports;
using System.Drawing;
using System.Threading;
using System.Threading.Tasks;

namespace Reader.SFC.Forms
{
    /*
     * 1.状态控制 ui 的异步更新
     * 2.读取列表 区分不同的天线
     * 3.reader 光电开关以及 触发等条件控制
     * 4.上传条件判断与上传 区分不同的天线对应不同的 port
     */
    public partial class FrmRFID71 : Form
    {
        private SerialPort serialPort1;
        private SerialPort serialPort2;

        private Action<string, string, int> SendTo71;
        private Action<string, string, int> SendTo72;
        /// <summary>
        /// 缓存最后一次提交的数据，避免重复提交
        /// </summary>
        private string sLastProEPC1;
        private string sLastFixEPC1;
        private string sLastProEPC2;
        private string sLastFixEPC2;


        public static EPC[] Tag_Port1 = new EPC[2];//产品码+治具码 为一组
        public static EPC[] Tag_Port2 = new EPC[2];
        static List<SaveUdp> udps1 = new List<SaveUdp>();
        static List<SaveUdp> udps2 = new List<SaveUdp>();
        int iProEPCLen = 24;
        int iFixEPCLen = 16;
        private int[] hDev = new int[50];
        private NR2k.HANDLE_FUN fun;


        RichTextBoxLog rlog;
        Config config;

        int IPass1 = 0;
        int IPass2 = 0;
        /// <summary>
        /// 天线1读取的数据
        /// </summary>
        private static List<EPC> Tag_Reader1 = new List<EPC>();
        /// <summary>
        /// 天线2读取的数据
        /// </summary>
        private static List<EPC> Tag_Reader2 = new List<EPC>();

        public FrmRFID71()
        {
            InitializeComponent();
            SendTo71 = FrmRFID71_TagAction;//发送给大族
            SendTo72 = FrmRFID72_TagAction;//发送给世宗


        }
        void SendToPort(int port)
        {
            string str1 = string.Empty;
            string str2 = string.Empty;
            List<EPC> Tag_Reader = null;
            if (port == 1)
                Tag_Reader = Tag_Reader1;
            else
                Tag_Reader = Tag_Reader2;
            if (this.rad3.Checked) //三码绑定
            {
                //找到读取次数最多的产品码

                var maxProEPC = Tag_Reader.Where(p => p.epc.Length == iProEPCLen).OrderByDescending(p => p.count).FirstOrDefault();
                str1 = maxProEPC?.epc ?? "";
                //找到读取次数最多的治具码
                var maxFixEPC = Tag_Reader.Where(p => p.epc.Length == iFixEPCLen).OrderByDescending(p => p.count).FirstOrDefault();
                str2 = maxFixEPC?.epc ?? "";

                if (str1.IsNull() || str2.IsNull())
                {
                    //lock (Tag_Reader)
                    //{
                    //    Tag_Reader.Clear();
                    //    NotifyReaderView(port, false);
                    //    return;
                    //}
                    return;
                }
            }
            else if (this.rad2.Checked) //二码绑定
            {
                //找到读取次数最多的产品码
                var maxProEPC = Tag_Reader.Where(p => p.epc.Length == iProEPCLen).OrderByDescending(p => p.count).FirstOrDefault();
                str1 = maxProEPC?.epc ?? "";
                if (str1.IsNull())
                {
                    //lock (Tag_Reader)
                    //{
                    //    Tag_Reader.Clear();
                    //    NotifyReaderView(port, false);

                    //}
                    return;
                }
            }

            if (port == 1)
            {
                if (str1 != this.sLastProEPC1 && str2 != this.sLastFixEPC1)
                {
                    this.sLastProEPC1 = str1;
                    this.sLastFixEPC1 = str2;
                    if (config.System.AppStart == "71") //大族
                        SendTo71?.Invoke(str1, str2, port);
                    else                                //世宗
                        SendTo72?.Invoke(str1, str2, port);
                }
                //lock (Tag_Reader1)
                //    Tag_Reader1.Clear();
            }
            else
            {
                if (str1 != this.sLastProEPC2 && str2 != this.sLastFixEPC2)
                {
                    this.sLastProEPC2 = str1;
                    this.sLastFixEPC2 = str2;
                    if (config.System.AppStart == "71") //大族
                        SendTo71?.Invoke(str1, str2, port);
                    else                                //世宗
                        SendTo72?.Invoke(str1, str2, port);
                }
                //lock (Tag_Reader2)
                //    Tag_Reader2.Clear();
            }

        }
        //监听世宗
        private async void SerialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //接收数据
            string cmd = "";
            do
            {
                int count = serialPort1.BytesToRead;
                if (count <= 0)
                    break;
                byte[] readBuffer = new byte[count];

                Application.DoEvents();
                serialPort1.Read(readBuffer, 0, count);
                cmd += System.Text.Encoding.Default.GetString(readBuffer);

            } while (serialPort1.BytesToRead > 0);
            rlog.LogMessage($"世宗模式：接收指令 {cmd}");
            if (config.System.AppStart == "71")
                return;
            //string cmd = this.serialPort1.ReadLine();

            if (cmd.Contains("Read1"))
            {
                await Task.Factory.StartNew(() =>
                {
                    rlog.LogMessage("世宗模式：计时1启动");
                    //3秒后关闭光电触发
                    Thread.Sleep(config.RFID7.ReadCloseTime);
                    NR2k.SetDO(this.hDev[0], 1, 0);
                    rlog.LogMessage($"世宗模式：{config.RFID7.ReadCloseTime}毫秒后光电1关闭");
                    Thread.Sleep(config.RFID7.StopWaitTime);
                    SendToPort(1);
                });
            }
            else if (cmd.Contains("Read2"))
            {
                await Task.Factory.StartNew(() =>
                {
                    rlog.LogMessage("世宗模式：计时1启动");
                    //3秒后关闭光电触发
                    Thread.Sleep(config.RFID7.ReadCloseTime);
                    NR2k.SetDO(this.hDev[0], 2, 0);
                    rlog.LogMessage($"世宗模式：{config.RFID7.ReadCloseTime}毫秒后光电1关闭");
                    Thread.Sleep(config.RFID7.StopWaitTime);
                    SendToPort(2);
                });
            }

        }
        //监听reader
        public async void ReaderRecived(int hDev, int cmdID, IntPtr pData, int length, IntPtr pHost)
        {
            try
            {
                string epc = "";
                byte[] destination = new byte[32];
                byte[] numArray = new byte[32];
                if (length <= 2) return; //1 心跳
                Marshal.Copy(pData, destination, 0, length);
                Marshal.Copy(pHost, numArray, 0, 16);
                if (length == 4) //控制逻辑
                {
                    string str = string.Empty;
                    for (int index = 0; index < length; ++index)
                        str += string.Format("{0:X2} ", (object)destination[index]);
                    string strValue = str.Replace(" ", "");
                    if (strValue == "01424547")
                    {
                        Tag_Reader1.Clear();
                        if (config.System.AppStart == "71")
                        {
                            rlog.LogMessage("大族模式：计时1启动");
                            await Task.Factory.StartNew(() =>
                              {
                                  //3秒后关闭光电触发
                                  Thread.Sleep(config.RFID7.ReadCloseTime);
                                  NR2k.SetDO(this.hDev[0], 1, 0);
                                  rlog.LogMessage($"大族模式：{config.RFID7.ReadCloseTime}毫秒后光电1关闭");
                                  Thread.Sleep(config.RFID7.StopWaitTime);
                                  SendToPort(1);
                              });


                        }
                    }
                    else if (strValue == "01454E44")
                    {

                        rlog.LogMessage("光电1传输结束");
                    }
                    else if (strValue == "02424547")
                    {
                        Tag_Reader2.Clear();
                        if (config.System.AppStart == "71")
                        {
                            rlog.LogMessage("大族模式：计时2启动");
                            await Task.Factory.StartNew(() =>
                            {
                                //3秒后关闭光电触发
                                Thread.Sleep(config.RFID7.ReadCloseTime);
                                NR2k.SetDO(this.hDev[0], 2, 0);
                                rlog.LogMessage($"大族模式：{config.RFID7.ReadCloseTime}毫秒后光电2关闭");
                                Thread.Sleep(config.RFID7.StopWaitTime);
                                SendToPort(2);
                                Console.WriteLine("Tag_Reader2.Count={0}", Tag_Reader2.Count);
                            });

                        }
                    }
                    else if (strValue == "02454E44")
                    {
                        rlog.LogMessage("光电2传输结束");

                    }
                    rlog.LogMessage(strValue);
                    return;
                }
                for (int index = 0; index <= length - 5; ++index)
                    epc += string.Format("{0:X2} ", (object)destination[index]);
                epc = epc.Replace(" ", "");
                rlog.LogMessage(epc);

                int port = 1;
                if ((int)destination[length - 1] == 1)//1号触发器
                {
                    EPC oldTag = Tag_Reader1.FirstOrDefault(p => p.epc == epc);
                    int num = Convert.ToInt32(destination[length - 3].ToString(), 10) * 256 + Convert.ToInt32(destination[length - 2].ToString(), 10);
                    if (oldTag == null)
                    {
                        EPC newTag = new EPC();
                        newTag.epc = epc;
                        newTag.count = (long)num;
                        newTag.antNo = destination[length - 1];
                        newTag.devNo = Encoding.Default.GetString(numArray);
                        lock (Tag_Reader1)
                            Tag_Reader1.Add(newTag);
                    }
                    else
                        oldTag.count += (long)num;
                    port = 1;
                }
                if ((int)destination[length - 1] == 2)//2号触发器
                {
                    EPC oldTag = Tag_Reader2.FirstOrDefault(p => p.epc == epc);
                    int num = Convert.ToInt32(destination[length - 3].ToString(), 10) * 256 + Convert.ToInt32(destination[length - 2].ToString(), 10);
                    if (oldTag == null)
                    {
                        EPC newTag = new EPC();
                        newTag.epc = epc;
                        newTag.count = (long)num;
                        newTag.antNo = destination[length - 1];
                        newTag.devNo = Encoding.Default.GetString(numArray);
                        lock (Tag_Reader2)
                            Tag_Reader2.Add(newTag);
                    }
                    else
                        oldTag.count += (long)num;

                    port = 2;
                }

                NotifyReaderView(port);
            }
            catch (Exception ex)
            {
                rlog.LogMessage("读取标签异常:" + ex.Message);
            }
        }

        //上传给大族激光
        private void FrmRFID71_TagAction(string sProEPC, string sFixEPC, int iPort)
        {
            if (rad3.Checked && (sProEPC.IsNull() || sFixEPC.IsNull())) return;//尚未准备好

            var proBarcode = sProEPC.FromASCII(config.QR_Types.Where(p => p.Value == "產品碼").ToArray());
            if (proBarcode == null || proBarcode.StartsWith("\0")) return;
            var fixBarCode = sFixEPC.FromASCII(config.QR_Types.Where(p => p.Value == "治具碼").ToArray());
            if (fixBarCode == null || fixBarCode.StartsWith("\0")) return;
            if (rad3.Checked && (proBarcode.IsNull() || fixBarCode.IsNull())) return;//尚未准备好
            try
            {
                if (iPort == 1)
                {
                    this.serialPort1.WriteLine(proBarcode+"\r");
                    Thread.Sleep(config.RFID7.UpLoadInterval);
                    this.serialPort1.WriteLine(fixBarCode + "\r");
                }
                else
                {
                    this.serialPort2.WriteLine(proBarcode + "\r");
                    Thread.Sleep(config.RFID7.UpLoadInterval);
                    this.serialPort2.WriteLine(fixBarCode + "\r");
                }
                this.NotifySendView(fixBarCode, proBarcode, "", "成功", iPort);
                SetState(lblUpd, "OK");
                rlog.LogMessage(proBarcode);
            }
            catch (Exception ex)
            {
                this.NotifySendView(fixBarCode, proBarcode, "", "失败", iPort);
                SetState(lblUpd, "NG");
                rlog.LogWarning(ex.Message); ;
            }
            if (!this.rad3.Checked)
                return;
        }

        //上传给世宗激光
        private void FrmRFID72_TagAction(string sProEPC, string sFixEPC, int iPort)
        {
            string fixBarCode = "";
            string proBarcode = "";
            try
            {
                proBarcode = sProEPC.FromASCII(config.QR_Types.Where(p => p.Value == "產品碼").ToArray());
                if (proBarcode == null || proBarcode.StartsWith("\0")) return;
                fixBarCode = sFixEPC.FromASCII(config.QR_Types.Where(p => p.Value == "治具碼").ToArray());
                if (fixBarCode == null || fixBarCode.StartsWith("\0")) return;
                if (rad3.Checked && (proBarcode.IsNull() || fixBarCode.IsNull())) return;//尚未准备好

                string str = !this.rad3.Checked ? proBarcode + "," : proBarcode + "," + fixBarCode + ",";

                this.serialPort1.WriteLine(str);

                this.NotifySendView(fixBarCode, proBarcode, "", "成功", iPort);
                SetState(lblUpd, "OK");
                rlog.LogMessage(str);
            }
            catch (Exception ex)
            {
                this.NotifySendView(fixBarCode, proBarcode, "", "失败", iPort);
                SetState(lblUpd, "NG");
                rlog.LogWarning(ex.Message);
            }
        }

        private bool InitReader()
        {
            try
            {
                if (config.System.Port.IsNull())
                {
                    rlog.LogMessage("请在【设置】中设置端口号!");
                    return false;
                }

                if (config.System.Power == null || config.System.Power <= 0)
                {
                    config.System.Power = 30;
                }
                int index = 0;
                byte[] numArray = new byte[32];
                byte[] bytes = Encoding.ASCII.GetBytes(config.System.Port);
                while (index < 50 && this.hDev[index] != 0)
                    ++index;
                if (index == 50)
                {
                    rlog.LogMessage($"{config.System.Port}无法访问!");
                    SetState(lblRfid, "NG");
                    return false;
                }

                PANT_CFG pantCfg = new PANT_CFG(); //设置信号强度
                pantCfg.power = new uint[4];
                uint result = (uint)config.System.Power;
                if (result > 30U)
                    result = 30U;
                pantCfg.power[0] = result * 10U;
                pantCfg.power[1] = result * 10U;
                pantCfg.power[2] = result * 10U;
                pantCfg.power[3] = result * 10U;

                if (NR2k.ConnectDev(ref this.hDev[index], bytes) == 0)
                {
                    byte[] pVer = new byte[32];
                    NR2k.GetDevVersion(this.hDev[index], pVer);
                    SetState(lblRfid, "OK");
                }
                else
                {
                    SetState(lblRfid, "NG");
                    rlog.LogMessage($"{config.System.Port}连接失败!"); //btnTest.Visible = true;

                    return false;
                }

            }
            catch (Exception ex)
            {
                SetState(lblRfid, "NG");
                rlog.LogMessage($"启动异常:{ex.Message}");
                //btnTest.Visible = true;
                return false;
            }
            return true;
        }
        private bool UnInitReader()
        {
            bool flag = false;
            //断开设备
            for (int index = 0; index < 50; ++index)
            {
                if (this.hDev[index] != 0)
                {
                    NR2k.DisconnectDev(ref this.hDev[index]);
                    flag = true;
                }
            }
            if (!flag)
            {
                rlog.LogMessage($"断开COM失败!");
            }
            fun -= ReaderRecived;
            this.btnStart.Enabled = true;
            this.btnStop.Enabled = false;
            return flag;
        }
        private bool InitPort1()
        {
            serialPort1 = new SerialPort();
            this.serialPort1.DataReceived += SerialPort1_DataReceived;
            this.serialPort1.PortName = config.RFID7.Port1;
            this.serialPort1.BaudRate = config.RFID7.Baud1;
            try
            {
                this.serialPort1.Open();
                SetState(lblPort1, "OK");
                return true;
            }
            catch (Exception ex)
            {
                rlog.LogMessage($"連接端口1失敗:{ex.Message}");
                SetState(lblPort1, "NG");
            }
            return false;
        }



        private bool InitPort2()
        {
            serialPort2 = new SerialPort();
            this.serialPort2.PortName = config.RFID7.Port2;
            this.serialPort2.BaudRate = config.RFID7.Baud2;
            try
            {
                this.serialPort2.Open();
                SetState(lblPort2, "OK");
                return true;
            }
            catch (Exception ex)
            {
                rlog.LogMessage($"連接端口2失敗:{ex.Message}");
                SetState(lblPort2, "NG");
            }
            return false;
        }
        //初始化串口和硬件
        bool Init()
        {
            //btnTest.Visible = false;
            btnStart.Enabled = false;
            btnStop.Enabled = false;
            bool flag = false;
            //日志初始化
            if (rlog == null)
                rlog = new RichTextBoxLog(rtxt);
            config = Program.AppConfig;
            if (config == null)
            {
                flag = false;
            }
            else
            {
                this.Text = config.System.AppName + " " + config.System.Version;
                //lblMachineID.Text = config.Currency.host_id;
                lblPort.Text = config.System.Port;
                iProEPCLen = config.System.ProEPCLen24;
                iFixEPCLen = config.System.FixEPCLen16;

                flag = true;
            }
            //RFID设备连接状态
            if (flag && !InitReader())
            {
                flag = false;
            }
            //上传串口傳輸狀態
            InitPort1();
            InitPort2();

            //上传状态
            if (!flag)
            {
                btnStart.Enabled = false;
                btnStop.Enabled = false;
                rlog.LogMessage("初始化失败!");
            }
            else
            {
                btnStart.Enabled = true;
                btnStop.Enabled = false;
                rlog.LogMessage("准备就绪!");
            }
            return flag;
        }
        //注销操作
        void UnInit()
        {
            //if (PostTag != null)
            //    PostTag -= FrmReader_PostTag;
            //if (timUpd != null)
            //    timUpd.Elapsed -= TimUpd_Elapsed;
            btnStop_Click(null, null);
            UnInitReader();
            this.serialPort1.DataReceived -= SerialPort1_DataReceived;
            serialPort1.Close();
            serialPort2.Close();
        }



        //启动
        public bool Start()
        {
            try
            {

                bool flag = false;
                fun += ReaderRecived;
                for (int i = 0; i < 50; ++i)
                {
                    if (this.hDev[i] != 0)
                    {
                        NR2k.BeginInv(this.hDev[i], fun);
                        flag = true;
                    }
                }
                if (!flag)
                {
                    rlog.LogMessage("设备尚未连接!");
                    return false;
                }
                this.btnStart.Enabled = false;
                this.btnStop.Enabled = true;
                rlog.LogMessage("已启动");

                return true;

            }
            catch (Exception ex)
            {
                rlog.LogMessage($"启动异常:{ex.Message}");
                return false;
            }

        }
        //停止
        public bool Stop()
        {
            try
            {

                //停止监听
                bool flag = false;
                //serialPort?.Close();
                //return true;
                for (int index = 0; index < 50; ++index)
                {
                    if (this.hDev[index] != 0)
                    {
                        NR2k.StopInv(this.hDev[index]);
                        flag = true;
                    }
                }
                if (!flag)
                {
                    rlog.LogMessage("设备尚未连接!");
                    return false;

                }
                else
                {
                    this.btnStart.Enabled = true;
                    this.btnStop.Enabled = false;
                    rlog.LogMessage("已停止");
                    return true;
                }
            }
            catch (Exception ex)
            {
                rlog.LogMessage($"停止异常:{ex.Message}");
                return false;
            }
        }
        //Label的 颜色与文字 提示
        private void SetState(Label lbl, string msg = "就緒")
        {
            UpdateUI.UpdateUIControl(lbl, () =>
            {
                if (msg == "NG")
                {
                    lbl.BackColor = System.Drawing.Color.Salmon;
                    lbl.ForeColor = System.Drawing.SystemColors.ButtonFace;
                }
                else if (msg == "OK")
                {
                    lbl.BackColor = System.Drawing.Color.YellowGreen;
                    lbl.ForeColor = System.Drawing.SystemColors.ButtonFace;
                }
                else
                {
                    lbl.BackColor = System.Drawing.Color.Ivory;
                    lbl.ForeColor = System.Drawing.SystemColors.WindowFrame;
                }
                if (lbl.Name == "lblUpd")
                    lbl.Text = msg;
            });

        }

        //窗体加载
        private void FrmReader_Load(object sender, EventArgs e)
        {
            Init();
        }
        //窗体关闭
        private void FrmReader_FormClosing(object sender, FormClosingEventArgs e)
        {
            UnInit();
        }
        //点击设置
        private void btnSetting_Click(object sender, EventArgs e)
        {
            //FrmConfig open = new FrmConfig();
            //if (open.ShowDialog() == DialogResult.OK)
            //{
            //    UnInit();
            //    Init();
            //}
        }
        //点击开始
        private void btnStart_Click(object sender, EventArgs e)
        {
            Start();
        }
        //点击停止
        private void btnStop_Click(object sender, EventArgs e)
        {
            Stop();
        }
        //更新rederlistview
        void NotifyReaderView(int iPort, bool needClear = false)
        {
            if (iPort == 1)
                UpdateUI.UpdateUIControl(listRead1, () =>
                {
                    listRead1.Items.Clear();
                    for (int index = 0; index < Tag_Reader1.Count; ++index)
                        this.listRead1.Items.Add(new ListViewItem()
                        {
                            Text = (index + 1).ToString(),
                            SubItems ={
                              Tag_Reader1[index].epc,
                              Tag_Reader1[index].antNo.ToString(),
                              Tag_Reader1[index].count.ToString(),
                              Tag_Reader1[index].devNo.ToString()
                            }
                        });
                });
            else
                UpdateUI.UpdateUIControl(listRead2, () =>
                {
                    listRead2.Items.Clear();
                    for (int index = 0; index < Tag_Reader2.Count; ++index)
                        this.listRead2.Items.Add(new ListViewItem()
                        {
                            Text = (index + 1).ToString(),
                            SubItems ={
                              Tag_Reader2[index].epc,
                              Tag_Reader2[index].antNo.ToString(),
                              Tag_Reader2[index].count.ToString(),
                              Tag_Reader2[index].devNo.ToString()
                            }
                        });
                });
        }
        //更新发送列表
        void NotifySendView(string sFixEPC, string sProEPC, string sEquipNO, string webRes, int iPort)
        {
            if (iPort == 1)
                UpdateUI.UpdateUIControl(listPass1, () =>
                {

                    if (listPass1.Items.Count == 100)
                        listPass1.Items.Clear();
                    if (listPass1.Items.Count == 100)
                    {
                        listPass1.Items.Clear();
                        IPass1 = 0;
                        if (udps1 != null && udps1.Count > 0)
                        {
                            var time = DateTime.Now;
                            string json = udps1.ToJson();
                            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"UpdateLog({time.ToString("yyyyMMddHHmmss")}).json");

                            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path, false, Encoding.UTF8))
                            {
                                sw.Write(json);
                            }
                            rtxt.Clear();
                            udps1.Clear();
                            rlog.LogMessage("保存并清理成功!");
                        }
                    }

                    string sport = "Port1";
                    if (config.System.AppStart == "71")//大族
                        if (iPort == 1) sport = "Port1";
                        else sport = "Port2";
                    else
                         if (iPort == 1) sport = "Read1";
                    else sport = "Read2";

                    udps1.Add(new SaveUdp() //缓存上传记录
                    {
                        FixEPC = sFixEPC,
                        ProEPC = sProEPC,
                        EquipNO = sEquipNO,
                        Res = webRes,
                        Port = sport
                    });

                    this.listPass1.Items.Add(new ListViewItem((this.listPass1.Items.Count + 1).ToString())
                    {
                        SubItems = {
                      sFixEPC,
                      sProEPC,
                      sEquipNO,
                      webRes,
                      DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                      sport,
                    },
                        ForeColor = (webRes == "成功" ? System.Drawing.Color.Green : Color.Red)
                    });
                    if (webRes == "成功") //统计信息
                    {
                        IPass1++;
                        lblPas1.Text = $"上傳{sport} {(config.System.AppStart == "71" ? "大族激光" : "世宗激光")}      計數:【" + IPass1 + "】";
                    }

                    this.listPass1.Items[this.listPass1.Items.Count - 1].EnsureVisible();

                });
            else
                UpdateUI.UpdateUIControl(listPass2, () =>
                {

                    if (listPass2.Items.Count == 100)
                        listPass2.Items.Clear();
                    if (listPass2.Items.Count == 100)
                    {
                        listPass2.Items.Clear();
                        IPass2 = 0;
                        if (udps2 != null && udps2.Count > 0)
                        {
                            var time = DateTime.Now;
                            string json = udps2.ToJson();
                            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"UpdateLog({time.ToString("yyyyMMddHHmmss")}).json");

                            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path, false, Encoding.UTF8))
                            {
                                sw.Write(json);
                            }
                            rtxt.Clear();
                            udps2.Clear();
                            rlog.LogMessage("保存并清理成功!");
                        }
                    }

                    string sport = "Port1";
                    if (config.System.AppStart == "71")//大族
                        if (iPort == 1) sport = "Port1";
                        else sport = "Port2";
                    else
                         if (iPort == 1) sport = "Read1";
                    else sport = "Read2";

                    udps2.Add(new SaveUdp() //缓存上传记录
                    {
                        FixEPC = sFixEPC,
                        ProEPC = sProEPC,
                        EquipNO = sEquipNO,
                        Res = webRes,
                        Port = sport
                    });

                    this.listPass2.Items.Add(new ListViewItem((this.listPass2.Items.Count + 1).ToString())
                    {
                        SubItems = {
                      sFixEPC,
                      sProEPC,
                      sEquipNO,
                      webRes,
                      DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                      sport,
                    },
                        ForeColor = (webRes == "成功" ? System.Drawing.Color.Green : Color.Red)
                    });
                    if (webRes == "成功") //统计信息
                    {
                        IPass2++;
                        lblPas2.Text = $"上傳{sport} {(config.System.AppStart == "71" ? "大族激光" : "世宗激光")}      計數:【" + IPass2 + "】";
                    }

                    this.listPass2.Items[this.listPass2.Items.Count - 1].EnsureVisible();

                });

        }

    }
}